<template>
  <div class="admin-container">
    <h1>广告管理</h1>

    <!-- 查询和新增按钮区域 -->
    <div class="top-bar">
      <div class="search-container">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索广告商名称..."
          class="search-input"
        />
        <button @click="findPage">查询</button>
      </div>
      <button class="add-button" @click="openAddModal">新增广告</button>
    </div>

    <!-- 广告列表表格 -->
    <table>
      <thead>
        <tr>
          <th>广告商名称</th>
          <th>广告图片</th>
          <th>广告链接</th>
          <th>到期时间</th>
          <th>广告收益</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 空数据提示 -->
        <tr v-if="ads.length === 0" class="empty-row">
          <td colspan="6" class="empty-cell">暂无广告数据</td>
        </tr>
        <!-- 广告数据行 -->
        <tr v-else v-for="ad in ads" :key="ad.adid">
          <td>{{ ad.adcompany }}</td>
          <td><img :src="ad.adimage || defaultImage" alt="广告图片" class="ad-image" @error="e => e.target.src = defaultImage" /></td>
          <td>
            <a :href="ad.adlink" target="_blank" class="ad-link">
              {{ ad.adlink }}
            </a>
          </td>
          <td>{{ formatTime(ad.adtime) }}</td>
          <td>¥{{ ad.adincome.toFixed(2) }}</td>
          <td>
            <button @click="handleDelete(ad.adid)" class="delete-button">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <el-pagination
      :page-size="params.pageSize"
      :total="params.recordCount"
      v-model:current-page="params.pageNum"
      @current-change="findPage"
      @prev-click="prevPage"
      @next-click="nextPage"
      layout="total,prev,pager,next"
    />

    <!-- 新增广告弹窗 -->
    <el-dialog title="新增广告" v-model="showModal" width="600px" :center="true" :close-on-click-modal="false" :before-close="handClose">
      <el-form ref="adForm" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="广告商名称" prop="adcompany">
          <el-input v-model="form.adcompany" placeholder="请输入广告商名称" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="广告链接" prop="adlink">
          <el-input v-model="form.adlink" type="url" placeholder="请输入广告跳转链接（含http/https）" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="到期时间" prop="adtime">
          <el-date-picker
            v-model="form.adtime"
            type="datetime"
            placeholder="选择广告到期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            required
          />
        </el-form-item>

        <el-form-item label="广告收益" prop="adincome">
          <el-input
            v-model="form.adincome"
            type="number"
            placeholder="请输入广告收益（元）"
            step="0.01"
            min="0"
          />
        </el-form-item>

        <el-form-item label="广告图片" prop="adimage">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChangeFile"
            :accept="'.jpg,.jpeg,.png,.gif'"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持JPG、PNG、GIF格式，建议尺寸600*300px</div>
        </el-form-item>
      </el-form>

      <span class="dialog-footer">
        <el-button @click="handClose">取消</el-button>
        <el-button type="primary" @click="saveAd">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { uploadFileReq } from '@/api/File';
import { deleteById, queryPage, insertSave } from '@/api/advertise'
import { ElMessageBox, ElMessage, ElForm, ElFormItem, ElInput, ElDatePicker } from 'element-plus';

// 状态定义
const ads = ref([]); // 广告列表数据
const showModal = ref(false); // 新增弹窗显示状态
const form = ref({ // 新增广告表单数据
  adcompany: '',
  adlink: '',
  adtime: '',
  adincome: 0,
  adimage: ''
});
const searchQuery = ref(''); // 搜索关键词（按广告商名称搜索）
const params = ref({ // 分页参数
  pageNum: 1,
  pageSize: 5,
  recordCount: 0,
  pageCount: 0
});
const currentPage = ref(1); // 当前页码（同步分页组件）
const imageUrl = ref(''); // 广告图片预览地址
const adForm = ref(null); // 表单实例（用于校验）
const defaultImage = 'https://via.placeholder.com/120x60?text=广告图'; // 图片加载失败占位图

// 表单校验规则
const formRules = ref({
  adcompany: [
    { required: true, message: '请输入广告商名称', trigger: 'blur' },
  ],
  adlink: [
    { required: true, message: '请输入广告链接', trigger: 'blur' },
  ],
  adtime: [
    { required: true, message: '请选择到期时间', trigger: 'change' }
  ],
  adincome: [
    { required: true, message: '请输入广告收益', trigger: 'blur' },
  ],
  adimage: [
    { required: true, message: '请上传广告图片', trigger: 'change' }
  ]
});

// 页面挂载时初始化数据
onMounted(() => {
  searchPage();
});

// 分页查询广告数据
function searchPage() {
  queryPage(searchQuery.value, params.value.pageNum, params.value.pageSize)
    .then(response => {
      ads.value = response.list || [];
      params.value = { ...params.value, ...response.pager }; // 同步分页信息
      currentPage.value = params.value.pageNum; // 同步当前页码
    })
    .catch(error => {
      console.error('广告数据查询失败:', error);
      ElMessage.error('数据加载失败，请重试');
    });
}

// 分页事件（页码变化）
const findPage = () => {
  searchPage();
};

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value < params.value.pageCount) {
    currentPage.value++;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

// 图片上传处理
function handleChangeFile(uploadFile) {
  const file = uploadFile.raw;
  // 图片大小校验（限制5MB以内）
  if (file.size > 5 * 1024 * 1024) {
    return ElMessage.warning('图片大小不能超过5MB');
  }
  // 图片格式校验
  const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
  if (!validTypes.includes(file.type)) {
    return ElMessage.warning('仅支持JPG、PNG、GIF格式图片');
  }

  // 预览图片
  imageUrl.value = URL.createObjectURL(file);
  // 上传图片到服务器
  const formData = new FormData();
  formData.append('file', file);
  uploadFileReq(formData)
    .then(data => {
      form.value.adimage = data; // 保存图片地址到表单
    })
    .catch(error => {
      ElMessage.error('图片上传失败，请重试');
      imageUrl.value = ''; // 清空预览
    });
}

// 新增广告保存
const saveAd = async () => {
  // 表单校验
  if (!adForm.value) return;
  try {
    await adForm.value.validate();
    // 提交新增请求
    await insertSave(form.value);
    ElMessage.success('广告新增成功');
    handClose(); // 关闭弹窗
    searchPage(); // 刷新列表
  } catch (error) {
    // 表单校验失败不提示，接口失败提示
    if (error.name !== 'ValidateError') {
      console.error('广告新增失败:', error);
      ElMessage.error('广告新增失败，请重试');
    }
  }
};

// 删除广告（带确认弹窗）
const handleDelete = (adid) => {
  ElMessageBox.confirm(
    '确定要删除这条广告信息吗？此操作不可恢复！',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(() => {
    deleteById(adid)
      .then(() => {
        ElMessage.success('广告删除成功');
        searchPage(); // 刷新列表
      })
      .catch(error => {
        console.error('广告删除失败:', error);
        ElMessage.error('广告删除失败，请重试');
      });
  })
  .catch(() => {
    // 取消删除不处理
  });
};

// 打开新增弹窗
const openAddModal = () => {
  showModal.value = true;
  // 重置表单
  form.value = { adcompany: '', adlink: '', adtime: '', adincome: 0, adimage: '' };
  imageUrl.value = '';
  if (adForm.value) adForm.value.clearValidate();
};

// 关闭新增弹窗
function handClose() {
  showModal.value = false;
  imageUrl.value = '';
  if (adForm.value) adForm.value.clearValidate();
}

// 时间格式化（处理后端返回的时间戳或字符串）
function formatTime(time) {
  if (!time) return '-';
  // 若后端返回时间戳，转换为Date对象
  const date = typeof time === 'number' ? new Date(time) : new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}
</script>

<style scoped>
/* 基础容器样式 */
.admin-container {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  font-family: 'Arial', sans-serif;
}

/* 标题样式 */
h1 {
  text-align: center;
  font-size: 28px;
  margin-bottom: 20px;
  color: #333;
  position: relative;
}
h1::after {
  content: '';
  display: block;
  width: 80px;
  height: 3px;
  background: #007bff;
  margin: 10px auto 0;
  border-radius: 2px;
}

/* 顶部操作栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

/* 搜索容器 */
.search-container {
  display: flex;
  align-items: center;
}
.search-input {
  padding: 10px;
  width: 250px;
  border-radius: 4px;
  border: 1px solid #ccc;
  font-size: 14px;
  margin-right: 10px;
  transition: all 0.3s ease;
}
.search-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
  outline: none;
}

/* 按钮基础样式 */
button {
  background-color: #007bff;
  color: white;
  padding: 10px 12px;
  border: none;
  cursor: pointer;
  margin: 0;
  border-radius: 5px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}
button:hover {
  background-color: #0056b3;
}

/* 新增按钮特殊样式 */
.add-button {
  padding: 12px 18px;
  background-color: #28a745;
}
.add-button:hover {
  background-color: #218838;
}

/* 表格样式 */
table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
  table-layout: fixed;
  word-break: break-all;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
table, th, td {
  border: none;
}
th {
  padding: 14px;
  text-align: center;
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 500;
  font-size: 14px;
  border-bottom: 1px solid #e9ecef;
}
/* 表格列宽分配（适配6列数据） */
th:nth-child(1) { width: 18%; } /* 广告商名称 */
th:nth-child(2) { width: 15%; } /* 广告图片 */
th:nth-child(3) { width: 25%; } /* 广告链接 */
th:nth-child(4) { width: 20%; } /* 投放时间 */
th:nth-child(5) { width: 12%; } /* 广告收益 */
th:nth-child(6) { width: 10%; } /* 操作 */

td {
  padding: 14px;
  text-align: center;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e9ecef;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 广告图片样式 */
.ad-image {
  width: 120px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  transition: transform 0.3s ease;
}
.ad-image:hover {
  transform: scale(1.05);
}

/* 广告链接样式 */
.ad-link {
  display: inline-block;
  width: 100%;
  color: #007bff;
  text-decoration: none;}
.ad-link:hover {
text-decoration: underline;
}

/* 空数据行样式 */
.empty-row .empty-cell {
padding: 60px 20px;
text-align: center;
color: #6c757d;
font-size: 14px;
background: #fafafa;
}

/* 删除按钮样式 */
.delete-button {
background-color: #dc3545;
padding: 8px 12px;
}
.delete-button:hover {
background-color: #c82333;
}

/* 分页容器样式 */
.el-pagination {
margin-top: 25px;
display: flex;
justify-content: center;
}

/* 弹窗表单样式 */
.el-form {
margin-top: 15px;
}
.el-form-item {
margin-bottom: 20px;
}
.el-form-item__label {
color: #495057;
font-weight: 500;
}
.el-input, .el-date-picker {
width: 100%;
}

/* 图片上传区域样式 */
.avatar-uploader .el-upload {
border: 1px dashed var (--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var (--el-transition-duration-fast);
display: flex;
justify-content: center;
align-items: center;
height: 180px;
width: 180px;
background-color: #fafafa;
}
.avatar-uploader .el-upload:hover {
border-color: var (--el-color-primary);
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 60px;
height: 60px;
text-align: center;
}
.avatar {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 6px;
}
.upload-tip {
margin-top: 8px;
font-size: 12px;
color: #6c757d;
}

/* 弹窗底部按钮区域 */
.dialog-footer {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 10px;
}
.dialog-footer .el-button--plain {
color: #6c757d;
border-color: #dcdfe6;
}
.dialog-footer .el-button--primary {
background-color: #007bff;
border-color: #007bff;
}

/* 响应式适配（小屏幕优化） /
@media (max-width: 1200px) {
.admin-container {
width: 90%;
}
th:nth-child(3) { width: 22%; } / 缩小链接列宽度 /
th:nth-child(4) { width: 18%; } / 缩小时间列宽度 */

@media (max-width: 768px) {
.admin-container {
width: 95%;
padding: 15px;
}
h1 {
font-size: 24px;
}
.top-bar {
flex-direction: column;
align-items: stretch;
}
.search-input {
width: 100%;
margin-right: 0;
margin-bottom: 10px;
}
.search-container {
flex-direction: column;
align-items: stretch;
}



/* 弹窗宽度适配 */
.el-dialog {
width: 90% !important;
}
.avatar-uploader .el-upload {
width: 140px;
height: 140px;
}
}
</style>